<template>
  <ele-modal
    :width="460"
    title="地区数据导入"
    :body-style="{ paddingTop: '8px' }"
    :model-value="modelValue"
    @update:modelValue="updateModelValue">
    <div v-loading="loading">
      <el-upload
        drag
        :limit="1"
        accept=".xls,.xlsx"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :before-upload="doUpload"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="true"
        v-if="!showResult"
      >
        <ele-text
          type="placeholder"
          :icon="UploadFilled"
          :icon-props="{ size: 68, style: { opacity: 0.6 } }"
        />
        <ele-text type="placeholder">将文件拖到此处, 或点击上传</ele-text>
      </el-upload>
      <div v-if="!showResult" style="display: flex; align-items: center">
        <ele-text size="sm" type="secondary" style="line-height: 17px; flex: 1">
          <span style="padding-right: 8px">只能上传 xls、xlsx 文件,</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: inherit; line-height: inherit; vertical-align: 0"
            @click="onDownload"
          >
            下载模板
          </el-link>
        </ele-text>
      </div>
      <el-divider v-if="!showResult"></el-divider>
      <h3 style="color: #999999;font-size: 14px;margin-bottom: 8px;">上传进度</h3>
      <el-progress :stroke-width="10" :percentage="upload.uploadPercent"></el-progress>
      <h3 style="color: #999999;font-size: 14px;margin-bottom: 8px;">导入进度</h3>
      <el-progress :stroke-width="10" :percentage="upload.importPercent"></el-progress>
      <div v-if="showResult">
        <el-divider></el-divider>
        <div class="result-txt">本次数据导入已结束，本次共处理{{ uploadResult.countNum }}条数据</div>
        <div class="result-txt"><span>成功{{ uploadResult.successNum }}条,失败{{ uploadResult.failureNum }}条</span></div>
        <div class="result-txt">
          <el-link type="primary" :underline="false"
                   style="font-size:16px;vertical-align: baseline;margin-top: 15px;font-weight: bold;"
                   @click="exportUploadResult">下载导出结果
          </el-link>
        </div>
      </div>
    </div>
  </ele-modal>
</template>

<script setup>
import {ref, reactive} from 'vue';
import {UploadFilled} from '@element-plus/icons-vue';
import {ElMessageBox} from 'element-plus/es';
import {EleMessage} from 'ele-admin-plus/es';
import {importPlace, importPlaceProgress, downloadTemplate, downloadResult, fillFullName} from '@/api/system/place';
import {getToken} from "@/utils/token-util"
import {download} from '@/utils/common'

const emit = defineEmits(['done', 'update:modelValue']);

defineProps({
  /** 是否打开弹窗 */
  modelValue: Boolean
});

/** 导入请求状态 */
const loading = ref(false);


const upload = reactive({
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_API_URL + "/system/place/upload",
  /** 上传进度 */
  uploadPercent: 0,
  /** 导入进度 */
  importPercent: 0,
});

const uploadResult = reactive({
  countNum: 0,
  successNum: 0,
  failureNum: 0,
  resultFileName: null
});

/** 上传进度 */
// const uploadPercent = ref(0);

/** 导入进度 */
// const importPercent = ref(0);


/** 显示导入结果 */
const showResult = ref(false);

/** 上传 */
const doUpload = (file) => {
  if (
    ![
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ].includes(file.type)
  ) {
    EleMessage.error('只能选择 excel 文件');
    return false;
  }
  if (file.size / 1024 / 1024 > 10) {
    EleMessage.error('大小不能超过 10MB');
    return false;
  }
  loading.value = true;
  return true;
};

/** 更新modelValue */
const updateModelValue = (value) => {
  if (!value) {
    //代表当前需要关闭
    loading.value = false;
    upload.isUploading = false;
    upload.importPercent = 0;
    upload.uploadPercent = 0;
    showResult.value = false;
  }
  emit('update:modelValue', value);
};

/** 下载模板 */
const onDownload = () => {
  const loading = EleMessage.loading('请求中..');
  downloadTemplate()
    .then(() => {
      loading.close();
    })
    .catch((e) => {
      loading.close();
      EleMessage.error(e.message);
    });
};


//上传过程函数
const handleFileUploadProgress = (event, file, fileList) => {
  upload.uploadPercent = (event.loaded / event.total * 100) | 0
  upload.isUploading = true;
};


const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = true;
  loading.value = false;
  //标记上传进度100%
  upload.uploadPercent = 100;
  let hdl = setInterval(function () {
    importPlaceProgress(response.msg).then(response1 => {
      // console.log("监听导入进度", response1);
      upload.importPercent = parseInt(response1.msg);
    });
  }, 2000);


  importPlace(response.msg).then(response2 => {
    console.log("数据导入成功！", response2);
    clearInterval(hdl);
    upload.importPercent = 100;
    ElMessageBox({
      type: 'success',
      title: '操作结果',
      message: "导入成功！",
      customStyle: {maxWidth: '442px'}
    });
    uploadResult.resultFileName = response2.data.resultFileName;
    uploadResult.countNum = response2.data.countNum;
    uploadResult.successNum = response2.data.successNum;
    uploadResult.failureNum = response2.data.failureNum;
    showResult.value = true;
    emit('done');
  });
};


const exportUploadResult = () => {
  const loading = EleMessage.loading('请求中..');
  let params = {};
  params.fileName = uploadResult.resultFileName;
  downloadResult(params).then(() => {
    loading.close();
  })
    .catch((e) => {
      loading.close();
      EleMessage.error(e.message);
    });
  ;
};


</script>
<style>
.el-progress__text {
  text-align: center;
  color: #999999;
  font-size: 13px !important;
  min-width: 20px;
}
</style>
